﻿using System.Net.Http.Headers;
using GraphQL;
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.Newtonsoft;

namespace WikiApp.Lib;

public class GraphWiki : IDisposable
{
    private readonly GraphQLHttpClient client;

    public GraphWiki()
    {
        client = new GraphQLHttpClient("https://wiki.xauat.site/graphql", new NewtonsoftJsonSerializer());
        client.HttpClient.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", File.ReadAllText(@"C:\iOSClub\社团活动\2024年5月 建大Wiki第一期\密钥.txt"));
    }

    public async Task<InitModel> Init()
    {
        var heroRequest = new GraphQLRequest
        {
            Query = """
                    {
                      	pages {
                          tree(mode : ALL,locale : "zh") {
                            path,
                            isFolder,
                            id,
                            title
                          }
                          list (orderBy : PATH){
                          	id
                            title
                            path
                            description
                            updatedAt
                            contentType
                        	}
                        }
                    }
                    """
        };
        var a = await client.SendQueryAsync<InitModel>(heroRequest);
        return a.Data;
    }

    public async Task<PageSingle> GetPageSingle(string id)
    {
        var heroRequest = new GraphQLRequest
        {
            Query = $$"""
                      {
                        pages {
                          single (id : {{id}}){
                            id
                            title
                            path
                            content
                            updatedAt
                          }
                        }
                      }
                      """
        };
        return (await client.SendQueryAsync<PageSingleData>(heroRequest)).Data.Pages.Single;
    }

    public async Task<PageTree[]> GetPageTree(int id)
    {
        var heroRequest = new GraphQLRequest
        {
            Query = $$"""
                      {
                        pages {
                          tree (mode : ALL,locale : "zh",parent : {{id}}){
                            id
                            isFolder
                            path
                            title
                          }
                        }
                      }
                      """
        };
        return (await client.SendQueryAsync<InitModel>(heroRequest)).Data.Pages.Tree;
    }

    public void Dispose()
    {
        client.Dispose();
        GC.SuppressFinalize(this);
    }
}